<template>
	<div id="picture-manage-view">
		<!-- 标题栏 -->
		<a-flex justify="space-between" align="center" style="margin-bottom: 16px">
			<h2>图片管理</h2>
			<a-space>
				<a-button type="primary" href="/add_picture" target="_blank">+ 创建图片</a-button>
				<a-button type="primary" href="/add_picture/batch" target="_blank" ghost>+ 批量创建图片</a-button>
			</a-space>
		</a-flex>

		<!-- 批量操作栏 -->
		<div
			v-if="selectedRowKeys.length > 0"
			style="margin-bottom: 16px; padding: 12px; background: #f0f8ff; border-radius: 6px; border: 1px solid #d9e7f7"
		>
			<a-space>
				<span style="color: #1890ff; font-weight: 500">已选择 {{ selectedRowKeys.length }} 项</span>
				<a-button
					type="primary"
					:loading="batchLoading"
					@click="handleBatchReview(PIC_REVIEW_STATUS_ENUM.PASS)"
					:disabled="getCanProcessCount(PIC_REVIEW_STATUS_ENUM.PASS) === 0"
				>
					批量审核通过 ({{ getCanProcessCount(PIC_REVIEW_STATUS_ENUM.PASS) }})
				</a-button>
				<a-button
					type="primary"
					danger
					:loading="batchLoading"
					@click="handleBatchReview(PIC_REVIEW_STATUS_ENUM.REJECT)"
					:disabled="getCanProcessCount(PIC_REVIEW_STATUS_ENUM.REJECT) === 0"
				>
					批量审核拒绝 ({{ getCanProcessCount(PIC_REVIEW_STATUS_ENUM.REJECT) }})
				</a-button>
				<a-button
					type="primary"
					danger
					:loading="batchLoading"
					@click="handleBatchDelete"
					:disabled="selectedRowKeys.length === 0"
				>
					批量删除 ({{ selectedRowKeys.length }})
				</a-button>
				<a-button @click="clearSelection">清空选择</a-button>
			</a-space>
		</div>
		<!-- 搜索表单 -->
		<PictureSearchForm :show-review-status="true" @search="onSearch" @reset="onSearch" style="margin-bottom: 16px" />

		<div style="margin-bottom: 16px"></div>

		<!-- 表格 -->
		<a-table
			:columns="columns"
			:data-source="dataList"
			:pagination="pagination"
			@change="doTableChange"
			:loading="loading"
			:scroll="{ x: 'max-content' }"
			:row-selection="{
				selectedRowKeys: selectedRowKeys,
				onChange: onSelectChange,
			}"
			row-key="id"
		>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'introduction'">
					<span style="white-space: pre-wrap; word-break: break-all; max-width: 200px; display: inline-block">
						{{ record.introduction }}
					</span>
				</template>
				<template v-if="column.dataIndex === 'url'">
					<a-image v-if="record.url" :src="record.thumbnailUrl || record.url" :width="120" />
				</template>
				<template v-if="column.dataIndex === 'tags'">
					<a-space wrap>
						<a-tag v-for="tag in JSON.parse(record.tags || '[]')" :key="tag">{{ tag }}</a-tag>
					</a-space>
				</template>
				<template v-if="column.dataIndex === 'picInfo'">
					<div>格式：{{ record.picFormat }}</div>
					<div>宽度：{{ record.picWidth }} px</div>
					<div>高度：{{ record.picHeight }} px</div>
					<div>宽高比：{{ record.picScale }}</div>
					<div>大小：{{ (record.picSize / 1024).toFixed(2) }}KB</div>
				</template>
				<template v-if="column.dataIndex === 'reviewMessage'">
					<div>审核状态：{{ PIC_REVIEW_STATUS_MAP[record.reviewStatus] }}</div>
					<div>审核信息：{{ record.reviewMessage }}</div>
					<div>审核人：{{ record.reviewerId }}</div>
					<div v-if="record.reviewTime">审核时间：{{ dayjs(record.reviewTime).format('YYYY-MM-DD HH:mm:ss') }}</div>
				</template>
				<template v-if="column.dataIndex === 'createTime'">
					{{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
				</template>
				<template v-if="column.dataIndex === 'editTime'">
					{{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
				</template>

				<template v-else-if="column.key === 'action'">
					<a-space wrap style="max-width: 80px">
						<a-button
							v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.PASS"
							type="link"
							@click="handleReview(record, PIC_REVIEW_STATUS_ENUM.PASS)"
						>
							通过
						</a-button>
						<a-button
							v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.REJECT"
							type="link"
							danger
							@click="handleReview(record, PIC_REVIEW_STATUS_ENUM.REJECT)"
						>
							拒绝
						</a-button>
						<a-button type="link" :href="`/add_picture?id=${record.id}`" target="_blank"> 编辑 </a-button>
						<a-button danger @click="doDelete(record.id)"> 删除 </a-button>
					</a-space>
				</template>
			</template>
		</a-table>

		<!-- 新增/编辑图片弹窗 -->
		<a-modal
			v-model:open="modalVisible"
			:title="isEdit ? '编辑图片' : '新增图片'"
			:confirmLoading="modalLoading"
			width="600px"
		>
			<a-form ref="formRef" :model="pictureForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
				<a-form-item
					label="图片账号"
					name="pictureAccount"
					:rules="[
						{ required: true, message: '请输入图片账号!' },
						{ min: 4, message: '账号长度不能少于4位!' },
					]"
				>
					<a-input v-model:value="pictureForm.pictureAccount" placeholder="请输入图片账号" :disabled="isEdit" />
				</a-form-item>

				<a-form-item label="图片名" name="pictureName" :rules="[{ required: true, message: '请输入图片名!' }]">
					<a-input v-model:value="pictureForm.pictureName" placeholder="请输入图片名" />
				</a-form-item>
				<a-form-item label="图片头像" name="pictureAvatar">
					<a-input v-model:value="pictureForm.pictureAvatar" placeholder="请输入头像URL" />
				</a-form-item>

				<a-form-item label="图片简介" name="pictureProfile">
					<a-textarea
						v-model:value="pictureForm.pictureProfile"
						placeholder="请输入图片简介"
						:rows="3"
						:max-length="200"
						show-count
					/>
				</a-form-item>

				<a-form-item label="图片角色" name="pictureRole" :rules="[{ required: true, message: '请选择图片角色!' }]">
					<a-select v-model:value="pictureForm.pictureRole" placeholder="请选择图片角色">
						<a-select-option value="picture">普通图片</a-select-option>
						<a-select-option value="admin">管理员</a-select-option>
					</a-select>
				</a-form-item>
			</a-form>
		</a-modal>

		<!-- 审核弹窗 -->
		<a-modal
			v-model:open="reviewModalVisible"
			:title="`${currentReviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '审核通过' : '审核拒绝'} - ${
				currentReviewRecord?.name
			}`"
			:confirmLoading="reviewModalLoading"
			@ok="handleReviewConfirm"
			@cancel="handleReviewCancel"
			width="500px"
		>
			<a-form :model="reviewForm" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
				<a-form-item label="图片信息">
					<div class="review-picture-info">
						<a-image
							v-if="currentReviewRecord?.url"
							:src="currentReviewRecord.thumbnailUrl || currentReviewRecord.url"
							:width="100"
						/>
						<div class="picture-details">
							<p><strong>名称：</strong>{{ currentReviewRecord?.name }}</p>
							<p><strong>类型：</strong>{{ currentReviewRecord?.category }}</p>
							<p><strong>简介：</strong>{{ currentReviewRecord?.introduction }}</p>
						</div>
					</div>
				</a-form-item>
				<a-form-item label="审核意见" name="reviewMessage" :rules="[{ required: true, message: '请填写审核意见!' }]">
					<a-textarea
						v-model:value="reviewForm.reviewMessage"
						:placeholder="`请填写${currentReviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '通过' : '拒绝'}的理由`"
						:rows="4"
						:max-length="200"
						show-count
					/>
				</a-form-item>
			</a-form>
		</a-modal>
	</div>
</template>

<script lang="ts" setup>
import { deletePictureUsingPost, listPictureByPageUsingPost, doPictureReviewUsingPost } from '@/api/pictureController'
import { message, Modal } from 'ant-design-vue'
import { computed, onMounted, reactive, ref } from 'vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { createVNode } from 'vue'
import dayjs from 'dayjs'
import { PIC_REVIEW_STATUS_ENUM, PIC_REVIEW_STATUS_MAP, PIC_REVIEW_STATUS_OPTIONS } from '@/constants/picture'
import PictureSearchForm from '@/components/picture/PictureSearchForm.vue'

// 表格加载状态
const loading = ref(false)

// 行选择相关状态
const selectedRowKeys = ref<(string | number)[]>([])
const batchLoading = ref(false)

// 弹窗相关状态
const modalVisible = ref(false)
const modalLoading = ref(false)
const isEdit = ref(false)
const formRef = ref()

// 审核弹窗相关状态
const reviewModalVisible = ref(false)
const reviewModalLoading = ref(false)
const currentReviewRecord = ref<API.Picture>()
const currentReviewStatus = ref<number>()
const reviewForm = reactive({
	reviewMessage: '',
})

// 图片表单数据
const pictureForm = reactive<{
	id?: number
	pictureAccount?: string
	pictureName?: string
	pictureAvatar?: string
	pictureProfile?: string
	pictureRole?: string
}>({})

// 表单列
const columns = [
	{ title: '图片编号', dataIndex: 'id', align: 'left' },
	{ title: '图片', dataIndex: 'url', align: 'left' },
	{ title: '名称', dataIndex: 'name', align: 'left' },
	{ title: '简介', dataIndex: 'introduction', ellipsis: true, align: 'left' },
	{ title: '类型', dataIndex: 'category', align: 'left' },
	{ title: '标签', dataIndex: 'tags', align: 'left' },
	{ title: '图片信息', dataIndex: 'picInfo', align: 'left' },
	{ title: '用户编号', dataIndex: 'userId', align: 'left' },
	{ title: '审核信息', dataIndex: 'reviewMessage', align: 'left' },
	{ title: '创建时间', dataIndex: 'createTime', align: 'left' },
	{ title: '编辑时间', dataIndex: 'editTime', align: 'left' },
	{ title: '操作', key: 'action', align: 'center' },
]

// 表单数据
const dataList = ref<API.Picture[]>([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
	current: 1,
	pageSize: 10,
	sortField: 'createTime',
	sortOrder: 'descend',
	searchText: '',
	category: '',
	tags: [],
})

// 分页参数
const pagination = computed(() => {
	return {
		current: searchParams.current ?? 1,
		pageSize: searchParams.pageSize ?? 10,
		total: total.value,
		showSizeChanger: true,
		showTotal: (total: number) => `总共 ${total} 条`,
	}
})

// 表格变化之后，重新获取数据
const doTableChange = (page: { current: number; pageSize: number }) => {
	searchParams.current = page.current
	searchParams.pageSize = page.pageSize
	fetchData()
}

// 行选择处理
const onSelectChange = (newSelectedRowKeys: (string | number)[], selectedRows: API.Picture[]) => {
	// console.log('选择变化:', newSelectedRowKeys, selectedRows)
	selectedRowKeys.value = newSelectedRowKeys
}

// 清空选择
const clearSelection = () => {
	selectedRowKeys.value = []
}

// 获取可以处理的图片数量（用于显示在按钮上）
const getCanProcessCount = (targetStatus: number) => {
	const selectedPictures = dataList.value.filter((item) => item.id && selectedRowKeys.value.includes(item.id))
	return selectedPictures.filter((item) => item.reviewStatus !== targetStatus).length
}

// 获取数据
const fetchData = async () => {
	loading.value = true
	try {
		const res = await listPictureByPageUsingPost({
			...searchParams,
			nullSpaceId: true,
		})
		if (res.data.code === 0 && res.data.data) {
			dataList.value = res.data.data.records ?? []
			total.value = res.data.data.total ?? 0
		} else {
			message.error('获取数据失败' + res.data.message)
		}
	} catch {
		message.error('网络错误，请稍后再试')
	} finally {
		loading.value = false
	}
}

// 处理搜索事件
const onSearch = (newSearchParams: any) => {
	// 直接更新搜索参数，不做任何转换
	Object.assign(searchParams, newSearchParams)
	// 重新获取数据
	fetchData()
}

// 搜索操作（保留原有方法供内部使用）
const doSearch = () => {
	// 重置当前页为1
	searchParams.current = 1
	// 重新获取数据
	fetchData()
}

// 重置搜索条件（保留原有方法供内部使用）
const resetSearch = () => {
	// 重置搜索参数
	Object.assign(searchParams, {
		current: 1,
		pageSize: 10,
		sortField: 'createTime',
		sortOrder: 'descend',
		searchText: '',
		category: '',
		tags: [],
		reviewStatus: undefined,
	})
	// 重新获取数据
	fetchData()
}

// 删除操作
const doDelete = async (id: number) => {
	if (!id) {
		return
	}

	Modal.confirm({
		title: '⚠️ 危险操作确认',
		icon: createVNode(ExclamationCircleOutlined),
		content: `确定要删除这个图片吗？此操作不可恢复，请谨慎操作！\n\n图片ID: ${id}`,
		okText: '确认删除',
		okType: 'danger',
		cancelText: '取消',
		width: 400,
		async onOk() {
			try {
				const res = await deletePictureUsingPost({ id })
				if (res.data.code === 0) {
					message.success('删除成功')
					// 删除成功后重新获取数据
					await fetchData()
				} else {
					message.error('删除失败：' + res.data.message)
				}
			} catch {
				message.error('删除失败，请重试')
			}
		},
	})
}

// 审核图片 - 显示审核弹窗
const handleReview = async (record: API.Picture, reviewStatus: number) => {
	currentReviewRecord.value = record
	currentReviewStatus.value = reviewStatus
	// 设置默认审核信息
	reviewForm.reviewMessage = reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '审核通过' : '审核拒绝'
	reviewModalVisible.value = true
}

// 确认审核操作
const handleReviewConfirm = async () => {
	if (!reviewForm.reviewMessage.trim()) {
		message.error('请填写审核意见!')
		return
	}

	reviewModalLoading.value = true
	try {
		const res = await doPictureReviewUsingPost({
			id: currentReviewRecord.value?.id,
			reviewStatus: currentReviewStatus.value,
			reviewMessage: reviewForm.reviewMessage,
		})
		if (res.data.code === 0) {
			message.success('审核操作成功')
			reviewModalVisible.value = false
			// 审核成功后重新获取数据
			fetchData()
		} else {
			message.error('审核操作失败: ' + res.data.message)
		}
	} catch (error) {
		message.error('审核操作失败，请重试')
	} finally {
		reviewModalLoading.value = false
	}
}

// 取消审核操作
const handleReviewCancel = () => {
	reviewModalVisible.value = false
	reviewForm.reviewMessage = ''
	currentReviewRecord.value = undefined
	currentReviewStatus.value = undefined
}

// 批量删除操作
const handleBatchDelete = async () => {
	if (selectedRowKeys.value.length === 0) {
		message.warning('请先选择要删除的图片')
		return
	}

	// 获取选中的图片信息
	const selectedPictures = dataList.value.filter((item) => item.id && selectedRowKeys.value.includes(item.id))

	let confirmContent = `您选择了 ${selectedRowKeys.value.length} 个图片进行删除操作。`
	confirmContent += `\n\n⚠️ 此操作不可恢复，请确认是否继续？`

	if (selectedPictures.length > 0) {
		confirmContent += `\n\n即将删除的图片：`
		selectedPictures.slice(0, 5).forEach((pic) => {
			confirmContent += `\n• ${pic.name || '未命名'} (ID: ${pic.id})`
		})
		if (selectedPictures.length > 5) {
			confirmContent += `\n• 还有 ${selectedPictures.length - 5} 个图片...`
		}
	}

	Modal.confirm({
		title: '⚠️ 批量删除确认',
		icon: createVNode(ExclamationCircleOutlined),
		content: confirmContent,
		okText: '确认删除',
		okType: 'danger',
		cancelText: '取消',
		width: 500,
		async onOk() {
			batchLoading.value = true
			let successCount = 0
			let failCount = 0

			try {
				// 获取需要删除的图片ID列表，保持原始类型不转换
				const idsToDelete = selectedRowKeys.value.filter((id) => id !== undefined)

				if (idsToDelete.length === 0) {
					message.info('没有需要删除的图片')
					return
				}

				// 并发执行删除操作，但限制并发数量
				const chunkSize = 5 // 每次并发处理5个
				const chunks: (string | number)[][] = []

				for (let i = 0; i < idsToDelete.length; i += chunkSize) {
					chunks.push(idsToDelete.slice(i, i + chunkSize))
				}

				for (const chunk of chunks) {
					const promises = chunk.map(async (id) => {
						try {
							// 确保传递给API的id是数字类型
							const numericId: any = id
							const res = await deletePictureUsingPost({ id: numericId })
							if (res.data.code === 0) {
								successCount++
							} else {
								failCount++
								console.error(`删除图片 ${id} 失败:`, res.data.message)
							}
						} catch (error) {
							failCount++
							console.error(`删除图片 ${id} 失败:`, error)
						}
					})

					await Promise.all(promises)
				}

				// 显示结果
				let resultMessage = ''
				if (failCount === 0) {
					resultMessage = `批量删除成功！共删除 ${successCount} 个图片`
					message.success(resultMessage)
				} else if (successCount === 0) {
					resultMessage = `批量删除失败！${failCount} 个图片删除失败`
					message.error(resultMessage)
				} else {
					resultMessage = `批量删除部分成功！成功删除 ${successCount} 个，失败 ${failCount} 个`
					message.warning(resultMessage)
				}

				// 清空选择并刷新数据
				clearSelection()
				await fetchData()
			} catch (error) {
				message.error('批量删除操作失败，请重试')
				console.error('批量删除失败:', error)
			} finally {
				batchLoading.value = false
			}
		},
	})
}

// 批量审核操作
const handleBatchReview = async (reviewStatus: number) => {
	if (selectedRowKeys.value.length === 0) {
		message.warning('请先选择要审核的图片')
		return
	}

	const statusText = reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '通过' : '拒绝'
	const defaultMessage = reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '批量审核通过' : '批量审核拒绝'

	// 获取选中的图片信息，分析当前审核状态
	const selectedPictures = dataList.value.filter((item) => item.id && selectedRowKeys.value.includes(item.id))

	// 过滤出可以进行目标审核操作的图片（排除已经是目标状态的图片）
	const canProcessPictures = selectedPictures.filter((item) => item.reviewStatus !== reviewStatus)
	const alreadyProcessedPictures = selectedPictures.filter((item) => item.reviewStatus === reviewStatus)

	// 如果没有可处理的图片
	if (canProcessPictures.length === 0) {
		message.warning(`选中的图片都已经是"${statusText}"状态，无需重复审核`)
		return
	}

	let confirmContent = `选中了 ${selectedRowKeys.value.length} 个图片，其中：`
	confirmContent += `\n• ${canProcessPictures.length} 个图片将被审核${statusText}`

	if (alreadyProcessedPictures.length > 0) {
		confirmContent += `\n• ${alreadyProcessedPictures.length} 个图片已经是"${statusText}"状态，将跳过处理`
	}

	confirmContent += `\n\n确定要继续批量审核${statusText}操作吗？`

	Modal.confirm({
		title: `批量审核${statusText}`,
		icon: createVNode(ExclamationCircleOutlined),
		content: confirmContent,
		okText: `确认${statusText}`,
		okType: reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? 'primary' : 'danger',
		cancelText: '取消',
		width: 500,
		async onOk() {
			batchLoading.value = true
			let successCount = 0
			let failCount = 0
			const skippedCount = alreadyProcessedPictures.length

			try {
				// 只处理可以审核的图片ID
				const idsToProcess = canProcessPictures.map((p) => p.id).filter((id) => id !== undefined) as number[]

				if (idsToProcess.length === 0) {
					message.info('没有需要处理的图片')
					return
				}

				// 并发执行审核操作，但限制并发数量
				const chunkSize = 5 // 每次并发处理5个
				const chunks: number[][] = []

				for (let i = 0; i < idsToProcess.length; i += chunkSize) {
					chunks.push(idsToProcess.slice(i, i + chunkSize))
				}

				for (const chunk of chunks) {
					const promises = chunk.map(async (id) => {
						try {
							const res = await doPictureReviewUsingPost({
								id: id, // 确保id是数字类型
								reviewStatus,
								reviewMessage: defaultMessage,
							})
							if (res.data.code === 0) {
								successCount++
							} else {
								failCount++
								console.error(`审核图片 ${id} 失败:`, res.data.message)
							}
						} catch (error) {
							failCount++
							console.error(`审核图片 ${id} 失败:`, error)
						}
					})

					await Promise.all(promises)
				}

				// 显示结果
				let resultMessage = ''
				if (failCount === 0) {
					resultMessage = `批量审核${statusText}成功！`
					resultMessage += `\n• 成功处理：${successCount} 个`
					if (skippedCount > 0) {
						resultMessage += `\n• 跳过处理：${skippedCount} 个（已是目标状态）`
					}
					message.success(resultMessage)
				} else if (successCount === 0) {
					resultMessage = `批量审核${statusText}失败！`
					resultMessage += `\n• 处理失败：${failCount} 个`
					if (skippedCount > 0) {
						resultMessage += `\n• 跳过处理：${skippedCount} 个`
					}
					message.error(resultMessage)
				} else {
					resultMessage = `批量审核${statusText}部分成功！`
					resultMessage += `\n• 成功处理：${successCount} 个`
					resultMessage += `\n• 处理失败：${failCount} 个`
					if (skippedCount > 0) {
						resultMessage += `\n• 跳过处理：${skippedCount} 个`
					}
					message.warning(resultMessage)
				}

				// 清空选择并刷新数据
				clearSelection()
				await fetchData()
			} catch (error) {
				message.error(`批量审核${statusText}操作失败，请重试`)
				console.error('批量审核失败:', error)
			} finally {
				batchLoading.value = false
			}
		},
	})
}

// 页面加载时获取数据，请求一次
onMounted(() => {
	// 初始化数据
	fetchData()
})
</script>

<style scoped lang="scss">
#picture-manage-view {
	// 表头标题居中
	:deep(.ant-table-thead > tr > th) {
		text-align: center !important;
	}

	// 图片列内容居中显示
	:deep(.ant-table-tbody > tr > td:nth-child(2)) {
		text-align: center !important;
	}

	// 审核弹窗样式
	.review-picture-info {
		display: flex;
		gap: 16px;
		padding: 16px;
		background: #f5f5f5;
		border-radius: 8px;
		margin-bottom: 16px;

		.picture-details {
			flex: 1;

			p {
				margin: 4px 0;
				line-height: 1.5;

				strong {
					color: #262626;
					margin-right: 8px;
				}
			}
		}
	}
}
</style>
